package com.tzxs.pay.main.print.utils.print;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.DynamicLayout;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.iposprinter.iposprinterservice.IPosPrinterCallback;
import com.iposprinter.iposprinterservice.IPosPrinterService;
import com.shengpay.smartpos.shengpaysdk.ITerminalAidl;
import com.tzxs.pay.R;

import com.tzxs.pay.util.BitmapUtils;
import com.tzxs.pay.util.PrintCommands;
import com.tzxs.pay.util.SystemUtil;

import java.io.InputStream;

import woyou.aidlservice.jiuiv5.ICallback;
import woyou.aidlservice.jiuiv5.IWoyouService;


public class AidlUtil {
    private static final String SERVICE＿PACKAGE = "woyou.aidlservice.jiuiv5";
    private static final String SERVICE＿ACTION = "woyou.aidlservice.jiuiv5.IWoyouService";
    private static final String TAG = AidlUtil.class.getName();

    private IWoyouService woyouService;
    private IPosPrinterService mIPosPrinterService;
    private ITerminalAidl terminalAidl;
    private static AidlUtil mAidlUtil = new AidlUtil();
    private Context context;

    private Callback callback;
    private ICallback woyouCallback = new ICallback.Stub() {
        @Override
        public void onRunResult(final boolean isSuccess) {
            callback.activity.runOnUiThread(new Runnable() {  //将ICallback中的回调操作切换至UI线程，便于AidlPrintTool的使用者在界面上做出打印失败时的提示
                @Override
                public void run() {
                    if (!isSuccess)
                        callback.onFail();
                }
            });
        }

        @Override
        public void onReturnString(String result) {
        }

        @Override
        public void onRaiseException(int code, final String msg) {
            Log.d(TAG, "onRaiseException(int, final String) called --- code: " + code + ", msg: " + msg);
            callback.activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    callback.onError(msg);
                }
            });
        }

        @Override
        public void onPrintResult(int code, String msg) {
        }
    };

    private AidlUtil() {
    }

    public static AidlUtil getInstance() {
        return mAidlUtil;
    }

    /**
     * 连接服务
     *
     * @param context context
     */
    public void connectPrinterService(Context context) {
        this.context = context.getApplicationContext();
        Intent intent = new Intent();
        //p1  v1 v1s系列初始化打印服务
        if (SystemUtil.getSystemModel().contains("P1") ||
                SystemUtil.getSystemModel().contains("V1") || SystemUtil.getSystemModel().contains("T2")) {
            intent.setPackage(SERVICE＿PACKAGE);
            intent.setAction(SERVICE＿ACTION);
            context.getApplicationContext().startService(intent);
            context.getApplicationContext().bindService(intent, connService, Context.BIND_AUTO_CREATE);
        }
        //集财打印初始化
        if (SystemUtil.getSystemModel().contains("JICAI")) {
            intent.setPackage("com.iposprinter.iposprinterservice");
            intent.setAction("com.iposprinter.iposprinterservice.IPosPrintService");
            context.getApplicationContext().startService(intent);
            context.getApplicationContext().bindService(intent, connService, Context.BIND_AUTO_CREATE);
        }
        if (SystemUtil.getSystemModel().contains("A8")) {
            intent.setClassName("com.shengpay.smartpos.shengpaysdk", "com.shengpay.smartpos.shengpaysdk.Service.TerminalService");

            context.getApplicationContext().bindService(intent, connService, Context.BIND_AUTO_CREATE);
//            IntentFilter intentFilter = new IntentFilter("com.shengpaysdk.print.status");
//            //intentFilter.addAction("com.shengpaysdk.qrcode.scan");
//            printerStatusReceiver = new PrinterStatusReceiver();
//            context.getApplicationContext().registerReceiver(printerStatusReceiver, intentFilter);
        }
    }
    /****测试前置摄像头扫码付款，发布时注释****/
//    public void scanDecoder() throws RemoteException{
//        terminalAidl.scanDecoder();
//    }
    /****************************************/

    /**
     * 断开服务
     *
     * @param context context
     */
    public void disconnectPrinterService(Context context) {
        if (woyouService != null) {
            context.getApplicationContext().unbindService(connService);
            woyouService = null;
        }
        if (SystemUtil.getSystemModel().contains("A8")) {
            if (terminalAidl != null) {
                context.getApplicationContext().unbindService(connService);
                terminalAidl = null;
            }
        }
    }

    public boolean isConnect() {
        return woyouService != null;
    }

    private ServiceConnection connService = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            woyouService = null;
            terminalAidl = null;
            Log.i("aaa", "失去服务");
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            if (SystemUtil.getSystemModel().contains("JICAI")) {
                mIPosPrinterService = IPosPrinterService.Stub.asInterface(service);
            }
            if (SystemUtil.getSystemModel().contains("P1") ||
                    SystemUtil.getSystemModel().contains("V1") ||
                    SystemUtil.getSystemModel().contains("T2")) {
                woyouService = IWoyouService.Stub.asInterface(service);
            }
            if (SystemUtil.getSystemModel().contains("A8")) {
                terminalAidl = ITerminalAidl.Stub.asInterface(service);
                try {
                    terminalAidl.setAppId(context.getPackageName());
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                Log.i("aaa", "连接服务");
            }

        }
    };

    private ICallback generateCB(final PrinterCallback printerCallback) {
        return new ICallback.Stub() {


            @Override
            public void onRunResult(boolean isSuccess) throws RemoteException {

            }

            @Override
            public void onReturnString(String result) throws RemoteException {
                printerCallback.onReturnString(result);
            }

            @Override
            public void onRaiseException(int code, String msg) throws RemoteException {

            }

            @Override
            public void onPrintResult(int code, String msg) throws RemoteException {

            }
        };
    }

    /**
     * 设置打印浓度
     */
    private int[] darkness = new int[]{0x0600, 0x0500, 0x0400, 0x0300, 0x0200, 0x0100, 0,
            0xffff, 0xfeff, 0xfdff, 0xfcff, 0xfbff, 0xfaff};

    //p1 v1  v1s设置大一技能浓度
    public void setDarkness(int index) {
        if (SystemUtil.getSystemModel().contains("P1") ||
                SystemUtil.getSystemModel().contains("V1")) {
            if (woyouService == null) {
                Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
                return;
            }

            int k = darkness[index];
            try {
                woyouService.sendRAWData(ESCUtil.setPrinterDarkness(k), null);
                woyouService.printerSelfChecking(null);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }


    }


    private IPosPrinterCallback posPrinterCallback = new IPosPrinterCallback.Stub() {
        @Override
        public void onRunResult(boolean isSuccess) throws RemoteException {
            Log.i("IPosPrinterCallback", "集财 pos机打印:" + isSuccess);

        }

        @Override
        public void onReturnString(String result) throws RemoteException {
            Log.i("IPosPrinterCallback", "集财 pos机打印:" + result);
        }
    };

    /**
     * 初始化打印机
     */
    public void initPrinter() {
        Log.i("2333", SystemUtil.getSystemModel());
        if (SystemUtil.getSystemModel().contains("P1") ||
                SystemUtil.getSystemModel().contains("V1")) {
            if (woyouService == null) {
                Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
                return;
            }

            try {
                woyouService.printerInit(null);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        if (SystemUtil.getSystemModel().contains("JICAI")) {
            if (mIPosPrinterService == null) {
                Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
                return;
            }
            try {
                mIPosPrinterService.printerInit(posPrinterCallback);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        if (SystemUtil.getSystemModel().contains("A8")
                ) {
            if (terminalAidl == null) {
                Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
                return;
            }

            try {

                terminalAidl.print_getStatus();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 打印二维码
     */
    public void printQr(String data, String modulesize, String errorlevel) {
        if (SystemUtil.getSystemModel().contains("P1") ||
                SystemUtil.getSystemModel().contains("V1") || SystemUtil.getSystemModel().contains("T2")) {
            if (woyouService == null) {
                Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
                return;
            }


            try {
                woyouService.setAlignment(1, null);
                woyouService.printQRCode(data, Integer.valueOf(modulesize), Integer.valueOf(errorlevel), null);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        if (SystemUtil.getSystemModel().contains("JICAI")) {
            if (mIPosPrinterService == null) {
                Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
                return;
            }

            try {
                //打印二维码
                mIPosPrinterService.setPrinterPrintAlignment(1, posPrinterCallback);
                mIPosPrinterService.printQRCode(data, 7, Integer.valueOf(errorlevel), posPrinterCallback);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        if (SystemUtil.getSystemModel().contains("A8")
                ) {
            if (terminalAidl == null) {
                Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
                return;
            }

            try {
                terminalAidl.print_setAlignment(1);
                terminalAidl.print_printQrCode(20, data, 200);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 打印条形码
     */
    public void printBarCode(String data, String symbology, String height, String width, String textposition) {
        if (SystemUtil.getSystemModel().contains("P1") ||
                SystemUtil.getSystemModel().contains("V1")) {
            if (woyouService == null) {
                Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
                return;
            }


            try {
                woyouService.printBarCode(data, Integer.valueOf(symbology), Integer.valueOf(height),
                        Integer.valueOf(width), Integer.valueOf(textposition), null);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        if (SystemUtil.getSystemModel().contains("JICAI")) {
            if (mIPosPrinterService == null) {
                Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
                return;
            }
            try {
                //打条码
                mIPosPrinterService.setPrinterPrintAlignment(1, posPrinterCallback);
                mIPosPrinterService.printBarCode(data, Integer.valueOf(symbology), Integer.valueOf(height),
                        Integer.valueOf(width), Integer.valueOf(textposition), posPrinterCallback);
//            mIPosPrinterService.printerPerformPrint(5, callback);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        if (SystemUtil.getSystemModel().contains("A8")) {
            if (terminalAidl == null) {
                Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
                return;
            }

            try {
                terminalAidl.print_printBarCode(data);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 打印文字
     */
    public void printText(String content, String size, String jcSize, String alignment, boolean isBold, boolean isUnderLine) {
        // Log.i("2333",content.replace("\n","换行"));

        if (!TextUtils.isEmpty(content)) {
            if (SystemUtil.getSystemModel().contains("P1") ||
                    SystemUtil.getSystemModel().contains("V1") || SystemUtil.getSystemModel().contains("T2")) {
                if (woyouService == null) {
                    Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
                    return;
                }

                try {
                    if (isBold) {
                        woyouService.sendRAWData(ESCUtil.boldOn(), null);
                    } else {
                        woyouService.sendRAWData(ESCUtil.boldOff(), null);
                    }

                    if (isUnderLine) {
                        woyouService.sendRAWData(ESCUtil.underlineWithOneDotWidthOn(), null);
                    } else {
                        woyouService.sendRAWData(ESCUtil.underlineOff(), null);
                    }
                    woyouService.setAlignment(Integer.valueOf(alignment), null);
                    woyouService.printTextWithFont(content, "gh", Integer.valueOf(size), null);
//                woyouService.lineWrap(3, null);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
            if (SystemUtil.getSystemModel().contains("JICAI")) {
                if (mIPosPrinterService == null) {
                    Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
                    return;
                }
                try {
                    mIPosPrinterService.setPrinterPrintDepth(10, posPrinterCallback);
                    mIPosPrinterService.PrintSpecFormatText(content, "ST", Integer.valueOf(jcSize), Integer.valueOf(alignment), posPrinterCallback);

                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
            if (SystemUtil.getSystemModel().contains("A8")) {
                if (terminalAidl == null) {
                    Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
                    return;
                }

                try {
                    terminalAidl.print_setAlignment(Integer.parseInt(alignment));
                    // terminalAidl.pri
                    if (isBold) {
                        terminalAidl.print_setFontSize(8);
                        terminalAidl.print_setGray(6);
                    } else {
                        terminalAidl.print_setFontSize(7);
                        terminalAidl.print_setGray(4);
                    }
                    terminalAidl.print_printText(content);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }

        }


    }

    public void printBitmapForA8(String bitmapType, int alignment) {  //A8打印位图
        if (terminalAidl == null) {
            Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
        } else {
            try {
                terminalAidl.print_setAlignment(alignment);
                String filename;
                switch (bitmapType) {
                    //支付宝
                    case "0":
                        filename = "icon_alipay.bmp";
                        break;
                    //微信
                    case "1":
                        filename = "icon_wechat.bmp";
                        break;
                    //银行卡
                    default:
                        filename = "icon_union.bmp";
                }
                InputStream inputStream = context.getAssets().open(filename);
                byte[] src = BitmapUtils.getInstance().InputStreamToBytes(inputStream);
                terminalAidl.print_printImage(0, src);
            } catch (Exception ex) {
                Log.e("Error", "ex: " + ex);
            }
        }
    }

    /*
     *打印图片
     */
    public void printBitmap(Bitmap bitmap, String alignment, String size, int bitmapId) {
        if (SystemUtil.getSystemModel().contains("P1") ||
                SystemUtil.getSystemModel().contains("V1") || SystemUtil.getSystemModel().contains("T2")) {
            if (woyouService == null) {
                Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
                return;
            }

            try {
                woyouService.setAlignment(Integer.parseInt(alignment), null);
                woyouService.printBitmap(bitmap, null);
                woyouService.lineWrap(1, null);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        //集财
        if (SystemUtil.getSystemModel().contains("JICAI")) {
            if (mIPosPrinterService == null) {
                Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
                return;
            }
            //打印图片
            try {
                mIPosPrinterService.printBitmap(Integer.valueOf(alignment), Integer.valueOf(size), bitmap, posPrinterCallback);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            bitmapRecycle(bitmap);
        }
    }

    /*加快bitmap回收，减少内存占用*/
    public void bitmapRecycle(Bitmap bitmap) {
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
        }
    }

    /**
     * 打印图片和文字按照指定排列顺序
     */
    public void printBitmap(Bitmap bitmap, int orientation) {
        if (woyouService == null) {
            Toast.makeText(context, "服务已断开！", Toast.LENGTH_LONG).show();
            return;
        }

        try {
            if (orientation == 0) {
                woyouService.printBitmap(bitmap, null);
                woyouService.printText("横向排列\n", null);
                woyouService.printBitmap(bitmap, null);
                woyouService.printText("横向排列\n", null);
            } else {
                woyouService.printBitmap(bitmap, null);
                woyouService.printText("\n纵向排列\n", null);
                woyouService.printBitmap(bitmap, null);
                woyouService.printText("\n纵向排列\n", null);
            }
            woyouService.lineWrap(3, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


    /*
     * 空打三行！
     */
    public void printBlankLine(String lines, String height) {
        if (SystemUtil.getSystemModel().contains("P1") ||
                SystemUtil.getSystemModel().contains("V1")) {
            if (woyouService == null) {
                Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
                return;
            }

            try {
                woyouService.lineWrap(Integer.valueOf(lines), null);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        if (SystemUtil.getSystemModel().contains("JICAI")) {
            try {
                //打印空白行
                mIPosPrinterService.printBlankLines(Integer.valueOf(lines), Integer.valueOf(height), posPrinterCallback);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        //联迪a8
        if (SystemUtil.getSystemModel().contains("A8")) {
            if (terminalAidl == null) {
                Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
                return;
            }

            try {

                if (!TextUtils.isEmpty(lines)) {
                    terminalAidl.print_feedline(Integer.valueOf(lines));
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }


    }


    /**
     * @param isBuffer 是否进入缓冲打印模式
     */
    public void enterPrinterBuffer(boolean isBuffer) {
        if (SystemUtil.getSystemModel().contains("P1") ||
                SystemUtil.getSystemModel().contains("V1")) {
            if (woyouService == null) {
                Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
                return;
            }
            try {
                woyouService.enterPrinterBuffer(isBuffer);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            if (SystemUtil.getSystemModel().contains("A8")) {
                try {
                    terminalAidl.print_setBatchPrint(isBuffer);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 提交打印
     */
    public void printCommit() {
        if (SystemUtil.getSystemModel().contains("P1") ||
                SystemUtil.getSystemModel().contains("V1")) {
            if (woyouService == null) {
                Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
                return;
            }
            try {
                woyouService.commitPrinterBuffer();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        if (SystemUtil.getSystemModel().contains("JICAI")) {
            try {
                //打印空白行
                mIPosPrinterService.printerPerformPrint(3, posPrinterCallback);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        //联迪a8
        if (SystemUtil.getSystemModel().contains("A8")) {
            if (terminalAidl == null) {
                Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
                return;
            }

            try {
                terminalAidl.print_batchPrint();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

    }


    public void sendRawData(byte[] data) {
        if (woyouService == null) {
            Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
            return;
        }

        try {
            woyouService.sendRAWData(data, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    public void sendRawDatabyBuffer(byte[] data, ICallback iCallback) {
        if (woyouService == null) {
            Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
            return;
        }

        try {
            woyouService.enterPrinterBuffer(true);
            woyouService.sendRAWData(data, iCallback);
            woyouService.exitPrinterBufferWithCallback(true, iCallback);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    //fontWidth、fontHeight范围：1-8
    public void printTextForT2(String text, int fontWidth, int fontHeight, byte alignment, Callback callback) throws RemoteException {
        if (woyouService == null) {
            Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
        } else {
            byte[] data = PrintCommands.bytesForPrintText(text, fontWidth, fontHeight, alignment);
            this.callback = callback;
            woyouService.sendRAWData(data, woyouCallback);
        }
    }

    public void printBitmapForT2(Bitmap bitmap, byte alignment, Callback callback) throws RemoteException {
        if (woyouService == null) {
            Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
        } else {
            byte[] data = PrintCommands.bytesForPrintBitmap(bitmap, alignment);
            this.callback = callback;
            woyouService.sendRAWData(data, woyouCallback);
        }
    }

    //unitSize范围：1-16
    public void printQRCodeForT2(String text, int unitSize, byte alignment, Callback callback) throws RemoteException {
        if (woyouService == null) {
            Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
        } else {
            byte[] data = PrintCommands.bytesForPrintQRCode(text, unitSize, alignment);
            this.callback = callback;
            woyouService.sendRAWData(data, woyouCallback);
        }
    }

    public void cutPaper(ICallback callback) {
        if (woyouService == null) {
            Toast.makeText(context, R.string.toast_2, Toast.LENGTH_LONG).show();
        } else {
            try {
                byte[] cutPaperCommand = PrintCommands.bytesForCutPaper();
                woyouService.sendRAWData(cutPaperCommand, callback);
            } catch (RemoteException ex) {
                Log.e(TAG, null, ex);
            }
        }
    }

    public static abstract class Callback {
        private Activity activity;

        public Callback(Activity activity) {
            this.activity = activity;
        }

        public abstract void onFail();

        public abstract void onError(String message);
    }
}
